package com.lv.suyiyong.hfr.ui

import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SizeUtils
import com.google.android.material.appbar.AppBarLayout
import com.lv.common.adapter.ViewPagerCommon2Adapter
import com.lv.common.base.BaseActivity
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.AppBarState
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.setupAppBarLayoutListener
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.service.model.ServiceViewModel
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.category.CategoryBean
import com.lv.service.room.category.CategoryDbHelper
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.ActivityMustFactoryTabBinding
import com.lv.suyiyong.hfr.fragment.MustFactoryFragment
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.math.abs

/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：必找工厂榜
 */
@Route(path = ARoutUtils.FactoryMustTabActivity)
class FactoryMustTabActivity : BaseActivity<ActivityMustFactoryTabBinding>() {
    private val mBannerTopData = mutableListOf<CommonSelectedBean>()
    private val threshold = SizeUtils.dp2px(100.0f)
    private val mTopUrl =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/1231/hengfuran/bzgc.png?x-oss-process=image/format,webp"
    private val mTopIv =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/facRankNav.png"
    private var mUserInfo: UserInfo? = null
    private val mTabs = mutableListOf<CommonSelectedBean>()
    private var mTabAdapter: ViewPagerCommon2Adapter? = null

    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_must_factory_tab
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@FactoryMustTabActivity, viewStatus)
            ivBackPage.setOnClickListener { finish() }
            val statusBarHeight =
                StatusBarUtil.getStatusBarHeight(this@FactoryMustTabActivity) + SizeUtils.dp2px(
                    50.0f
                )
            val miHight = SizeUtils.dp2px(160.0f) - statusBarHeight
            collToolbar.minimumHeight = miHight
        }
    }


    override fun initConfig() {
        super.initConfig()
        mBinding.ivTitlePage.LoadSrc(mTopIv)
        mBinding.ivTop.LoadSrc(mTopUrl)
//        initBannerAdapter()
//        bannerObserver()
        lifecycleScope.launch {
            val taskCategory = async {
                val mAllCategory = getCategoryForDB()
                mTabs.clear()
                mTabs.add(CommonSelectedBean("推荐", postiont = 0, selected = true))
                mAllCategory?.forEach {
                    mTabs.add(CommonSelectedBean(it.name, postiont = it.fcaid ?: 0))
                }
            }
            taskCategory.await()
            initPage()
        }

        UserDbHelper.getLiveUserInfo(this).observeKt {
            mUserInfo = it
        }
    }

    private suspend fun getCategoryForDB(): List<CategoryBean>? {
        return withContext(Dispatchers.IO) {
            //获取工厂分类
            CategoryDbHelper.getFindAllCategorySuspend(this@FactoryMustTabActivity)
        }
    }

    private fun initViewPager() {

        mTabAdapter = ViewPagerCommon2Adapter(
            supportFragmentManager,
            lifecycle,
            mTabs,
            object : ViewPagerCommon2Adapter.TabPagerListener {
                override fun getFragment(position: Int): Fragment {
                    return MustFactoryFragment.newInstance(mTabs[position].postiont)
                }

            }
        )
        mBinding.viewpager.adapter = mTabAdapter
        mBinding.viewpager.offscreenPageLimit = mTabs.size

        mBinding.ygxIndicator.setViewPager(mBinding.viewpager, mTabs)

    }


    override fun initEvents() {
        super.initEvents()
        mBinding.appBar.setupAppBarLayoutListener { state ->
            when (state) {
                AppBarState.EXPANDED -> {
                    // 展开状态，比如显示 FAB 或设置标题
                    mBinding.clTab.setBackgroundResource(com.lv.common.R.drawable.bg_half_t_ffd4b3_fff7f1_10)
                }

                AppBarState.COLLAPSED -> {
                    // 折叠状态
                    mBinding.clTab.setBackgroundResource(com.lv.common.R.drawable.bg_ffd4b3_fff7f1)
                }

                AppBarState.PARTIALLY_COLLAPSED -> {
                    // 中间状态
                    mBinding.clTab.setBackgroundResource(com.lv.common.R.drawable.bg_half_t_ffd4b3_fff7f1_10)
                }
            }

        }

        mBinding.appBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val abs = abs(verticalOffset)
            var mAlpha: Float = abs * 1.0f / threshold
            if (mAlpha < 0) {
                mAlpha = 0.0f
            }
            if (mAlpha > 1) {
                mAlpha = 1.0f
            }
            mBinding.ivTitlePage.alpha = mAlpha
            mBinding.viewStatus.alpha = mAlpha
        })

    }

    override fun initData() {
        super.initData()

    }

    private fun initPage() {
        initViewPager()
    }


}